package com.wt.struggle.goodbye.sq.activity

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.View
import com.google.gson.reflect.TypeToken
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.main.activity.AddCommentActivity
import com.wt.struggle.goodbye.main.activity.CommentListActivity
import com.wt.struggle.goodbye.main.activity.ShareActivity
import com.wt.struggle.goodbye.main.activity.TieDetailsActivity
import com.wt.struggle.goodbye.sq.adapter.PickUserAdapter
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.wt.struggle.goodbye.user.activity.SiXinOrRecoverActivity
import com.xin.lv.yang.utils.adapter.AdapterCallBack
import com.xin.lv.yang.utils.utils.StatusBarUtil
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.pick_details_layout.*

/**
 * 社区中的帖子信息界面
 */
class PickDetailsActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {

            Send.SEARCH_LIST -> {

                /// 获取的帖子信息列表返回
                refreshView.isRefreshing = false
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val arr = gson!!.fromJson<ArrayList<NewsInfo>>(
                            result,
                            object : TypeToken<ArrayList<NewsInfo>>() {}.type
                        )

                        if (arr.size != 0) {

                            add(arr)

                        } else {
                            showToastShort("暂无数据信息")
                        }

                    }
                }
            }

            Send.COLLECT_CODE -> {

                removeLoadDialog()
                showToastShort("操作成功")

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult

                    if (isCollectTie == 1) {

                        imageRight.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_y))

                    } else {

                        change()

                    }

                }
            }

            Send.ATTENTION_CODE -> {

                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {

                    if (isFoucus == 1) {
                        showToastShort("取消关注成功")
                    } else {
                        showToastShort("关注成功")
                    }

                    change()

                }
            }
        }
    }


    fun add(arr: ArrayList<NewsInfo>) {

        val list = arrayListOf<NewsInfo>()

        for (temp in arr) {

            if (temp.id == newsInfo!!.id) {
                list.add(0, temp)
            } else {
                list.add(temp)
            }
        }

        adapter.updateDataClear(list)
        moreList.addAll(list)
    }

    /**
     * 改变数据
     */
    private fun change() {

        val info = moreList[clickIndexPosition]
        when (clickCode) {
            1 -> {
                if (info.isCollection == 0) {
                    info.collectionCount++
                    info.isCollection = 1
                } else {
                    if (info.collectionCount != 0) {
                        info.collectionCount--
                        info.isCollection = 0
                    }
                }

            }

            2 -> {
                if (info.isLike == 0) {
                    info.likeCount++
                    info.isLike = 1
                } else {
                    if (info.likeCount != 0) {
                        info.likeCount--
                        info.isLike = 0
                    }
                }
            }

            3 -> {
                info.isDownZan = true
            }

            4 -> {
                info.numberOfCommented = info.numberOfCommented!! + 1
            }

            5 -> {
                if (info.status == 1) {
                    info.status = 0
                } else {
                    info.status = 1
                }
            }

            6 -> {

                /// 改变的用户信息
                val userInfo = info.userExtraInfo

                for (temp in moreList) {
                    val user11 = temp.userExtraInfo
                    if (user11!!.appUserId == userInfo!!.appUserId) {
                        if (user11.isCollection == 0) {
                            user11.isCollection = 1
                        } else {
                            user11.isCollection = 0
                        }
                    }
                }

            }
        }

        adapter.update(moreList, object : AdapterCallBack<NewsInfo>(list, moreList) {
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return oldList[oldItemPosition].id == newList[newItemPosition].id
            }

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return false
            }

            override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
                val bundle = Bundle()
                val oInfo = oldList[oldItemPosition]
                val nInfo = newList[newItemPosition]

                when (clickCode) {
                    1 -> {
                        bundle.putParcelable("isCollect", nInfo)
                    }
                    2 -> {
                        bundle.putParcelable("isLike", nInfo)
                    }
                    4 -> {
                        bundle.putInt("comment", nInfo.numberOfCommented!!)
                    }
                    6 -> {
                        bundle.putParcelable("attention", nInfo.userExtraInfo)
                    }
                }

                return bundle
            }

        })

    }

    /**
     *  1 为圈子操作   2 为帖子操作
     */
    var isCollectTie = 1

    var isFoucus = 0

    var newsInfo: NewsInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.pick_details_layout)

        val code = intent.getIntExtra("code", 1)

        when (code) {
            1 -> {
                newsInfo = intent.getParcelableExtra<NewsInfo>("info")
                if (tvTitle != null) {
                    tvTitle.text = newsInfo!!.name
                }
                imageRight.visibility = View.VISIBLE

                if (newsInfo!!.isCollection != 0) {
                    imageRight.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_y))
                } else {
                    imageRight.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_n))
                }

                imageRight.setOnClickListener {
                    isCollectTie = 1
                    send!!.collect(newsInfo!!.id.toString(), 2, handler)
                    showLoadDialog("收藏中")
                }

                getNewsList(newsInfo!!.id!!)
                showLoadDialog("")

                refreshView.setOnRefreshListener {
                    page = 1
                    getNewsList(newsInfo!!.id!!)
                    showLoadDialog("")

                }

            }

            2 -> {
                val userInfo = intent.getParcelableExtra<ProUserInfo>("userInfo")
                tvTitle.text = userInfo.nickName

                getListMyUserId(userInfo)
                showLoadDialog("")

                refreshView.setOnRefreshListener {
                    page = 1
                    getListMyUserId(userInfo)
                    showLoadDialog("")

                }

            }
            else -> {

            }
        }


        imageBack.setOnClickListener {
            finish()
        }

        initAdapter()
    }

    /**
     * 获取某个用户下的帖子
     */
    private fun getListMyUserId(userInfo: ProUserInfo?) {
        send!!.getSearchList(page, 10, 0, 0, userInfo!!.appUserId!!.toInt(), "", null, handler!!)
        showLoadDialog()

    }

    var page: Int = 1

    /**
     * 获取该社区下的帖子信息
     */
    private fun getNewsList(newsId: Int) {
        send!!.getSearchList(page, 10, newsId, 0, 0, "", null, handler!!)
        showLoadDialog()

    }


    lateinit var adapter: PickUserAdapter

    val list = arrayListOf<NewsInfo>()

    var clickIndexPosition = -1

    val moreList = arrayListOf<NewsInfo>()

    /**
     * 1 为收藏  2 为点赞  3 为不喜欢  4 为评论  6 为关注
     */
    var clickCode = 1

    private fun initAdapter() {
        detailsRecyclerView.layoutManager = LinearLayoutManager(this)
        detailsRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        adapter = PickUserAdapter(this, list)
        detailsRecyclerView.adapter = adapter

        adapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {

//                val intent = Intent(this@PickDetailsActivity, TieDetailsActivity::class.java)
//                intent.putExtra("code", 1)
//                intent.putExtra("data", list[position])
//                startActivity(intent)
//

            }

            override fun onLongClick(position: Int) {

            }

        }

        adapter.onFocusOnClickListener = object : PickUserAdapter.OnFocusOnClickListener {
            override fun onMore(position: Int) {
                openShare(position)

            }

            override fun onFocusOn(position: Int) {
                clickCode = 6

                this@PickDetailsActivity.clickIndexPosition = position
                val userInfo = list[position].userExtraInfo

                isFoucus = userInfo!!.isCollection

                send!!.attentionUser(userInfo, handler)

                if (isFoucus == 1) {
                    showLoadDialog("取消中")
                } else {
                    showLoadDialog("关注中")
                }

            }

            override fun onCollect(position: Int) {

                isCollectTie = 2
                clickCode = 1

                this@PickDetailsActivity.clickIndexPosition = position

                /// 收藏帖子信息
                send!!.collect(list[position].id.toString(), 1, handler)
                showLoadDialog("收藏中")

            }

            override fun onZan(position: Int) {

                isCollectTie = 2
                clickCode = 2

                this@PickDetailsActivity.clickIndexPosition = position
                send!!.clickZan(list[position].id!!, 1, handler)
                showLoadDialog("点赞中")


            }

            override fun onDownZan(position: Int) {

                isCollectTie = 2
                clickCode = 3

                val intent = Intent(this@PickDetailsActivity, SiXinOrRecoverActivity::class.java)
                intent.putExtra("code", 1)
                intent.putExtra("user", list[position].userExtraInfo)
                startActivity(intent)


            }

            override fun onComment(position: Int) {
                isCollectTie = 2
                clickCode = 4

                this@PickDetailsActivity.clickIndexPosition = position

                val intent = Intent(this@PickDetailsActivity, CommentListActivity::class.java)
                val info = list[position]
                intent.putExtra("info", info)

                intent.putParcelableArrayListExtra("vvvvList", info.videoList)
                intent.putParcelableArrayListExtra("audioList", info.audioList)

                startActivity(intent)

            }

        }

        detailsRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                if (Build.VERSION.SDK_INT >= 21) {

                    StatusBarUtil.setStatusBarLightMode(window, true)

                }

                val manager = recyclerView!!.layoutManager as LinearLayoutManager
                val firstVisibleItem = manager.findFirstVisibleItemPosition()
                val lastVisible = manager.findLastVisibleItemPosition()

                // 大于0说明有播放
                if (GSYVideoManager.instance().playPosition >= 0) {
                    //当前播放的位置
                    val position = GSYVideoManager.instance().playPosition

                    //对应的播放列表TAG
                    if (GSYVideoManager.instance().playTag == adapter.TAG &&
                        (position < firstVisibleItem || position > lastVisible)
                    ) {

                        if (GSYVideoManager.isFullState(this@PickDetailsActivity)) {
                            return
                        }

                        ///  如果滑出去了上面和下面就是否，和今日头条一样
                        GSYVideoManager.releaseAllVideos()

                    }
                }
            }
        })
    }

    /**
     * 打开分享弹窗
     */
    fun openShare(adapterPosition: Int) {
        val intent = Intent(this, ShareActivity::class.java)
        intent.putExtra("info", list[adapterPosition])
        intent.putExtra("code", 1)
        startActivity(intent)

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK && event!!.action == KeyEvent.ACTION_DOWN) {

            if (GSYVideoManager.isFullState(this)) {

                GSYVideoManager.backFromWindowFull(this)

            } else {
                finish()
            }

        }

        return super.onKeyDown(keyCode, event)
    }
}